
Partial Class Admin_Roles
    Inherits System.Web.UI.Page


    Private Sub ClearStatus()
        Me.RolesScrollingGridView.StatusText = ""
    End Sub

    Private Sub ShowStatus(ByVal message As String)
        Me.RolesScrollingGridView.StatusText = message
    End Sub

   
    ''' <summary>
    ''' For a role that is being set to inactive, check to see if there are any
    ''' current active users in that role.  If so, set an error message.
    ''' </summary>
    ''' <param name="roleId">Integer - the role that was set to inactive</param>
    ''' <returns>true if there are any current active users in the deactivated role.</returns>
    ''' <remarks></remarks>
    Private Function CheckForActiveUsers(ByVal roleId As Integer) As Boolean
        Dim errorMessage As String
        Dim userList As Generic.List(Of Cdm.DataCore.UserSecurity.CDMUser) = Cdm.DataCore.UserSecurity.CDMUser.ListActiveByRoleId(roleId)
        If userList IsNot Nothing Then
            If userList.Count > 0 Then
                errorMessage = "There are currently (" & userList.Count.ToString & ") active users in this role.  The role can not be made inactive until all users in the role are inactive."
                Me.ErrorSummary.SetSingleError(errorMessage)
                Me.ErrorSummary.Visible = True
                Return True
            End If
        End If
        Return False

    End Function

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        ClearStatus()
        SetupJavaScript()
        Me.ErrorSummary.Visible = False
        If Not Page.IsPostBack Then
            Me.RolesScrollingGridView.Sort("RoleName", SortDirection.Ascending)
        End If

      


    End Sub


    Private Sub SetupJavaScript()

        EntityController.JavaScriptAddChildDiv(Me.RolesScrollingGridView.DivClientId, CInt(Me.RolesScrollingGridView.ToolTip))
        ClientScript.RegisterStartupScript(Me.GetType(), "scrollDivs", EntityController.JavaScriptScrollingGridStartup(Me.RolesScrollingGridView), True)
        EntityController.JavaScriptSetFixedHeight(0)
        ScriptManager.RegisterClientScriptBlock(Me.RolesScrollingGridView, Me.RolesScrollingGridView.GetType(), _
        "scrollDivAsync", EntityController.JavaScriptScrollingGridStartup(Me.RolesScrollingGridView), True)
    End Sub

    Protected Sub RolesScrollingGridView_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles RolesScrollingGridView.RowCancelingEdit
        ' Hide the error summary.
        Me.ErrorSummary.Visible = False
        ShowStatus("Edit cancelled.")
    End Sub

    Protected Sub RolesScrollingGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles RolesScrollingGridView.RowDataBound
        If e.Row.DataItemIndex = 0 Then
            AccessibilityController.AddImageToSortableGridHeaders(RolesScrollingGridView)
        End If
        ' Get a reference to the role field that is in edit mode and set focus to it.
        Dim txtRoleDisplay As TextBox = CType(e.Row.FindControl("RoleDisplayTextBox"), TextBox)
        If Not txtRoleDisplay Is Nothing Then
            SetFocus(txtRoleDisplay.ClientID)
        End If

        'Set the values for the IsActive Checkbox or the image
        Dim currentRole As Cdm.DataCore.UserSecurity.Role = e.Row.DataItem
        Dim activeImage As Image = e.Row.FindControl("IsActiveImage")
        If Not activeImage Is Nothing Then
            If currentRole.IsActive = True Then
                activeImage.ImageUrl = "~/images/greencheck.gif"
                activeImage.AlternateText = "true"
            Else
                activeImage.ImageUrl = "~/images/blankcheck.gif"
                activeImage.AlternateText = "false"
            End If
        Else
            Dim activeCheckbox As CheckBox = e.Row.FindControl("EditActiveCheckbox")
            If Not activeCheckbox Is Nothing Then
                activeCheckbox.Checked = currentRole.IsActive
                activeCheckbox.InputAttributes.Add("title", "is role active?")
            End If
        End If

    End Sub

    Protected Sub RolesScrollingGridView_RowUpdated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdatedEventArgs) Handles RolesScrollingGridView.RowUpdated
        ShowStatus("Update successful.")
    End Sub

    Protected Sub RolesScrollingGridView_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles RolesScrollingGridView.RowUpdating
        Dim newValue As String
        Dim oldValue As String
        Dim isActiveCheckBox As CheckBox
        Dim errorMessage As String
        Dim itemIndex As Integer

        Dim oldIsActive As Boolean
        Dim newIsActive As Boolean

        If e.OldValues.Item(itemIndex) IsNot Nothing Then
            oldValue = e.OldValues.Item(itemIndex).ToString.ToUpper
        Else
            oldValue = ""
        End If

        '-----------------------------------------
        ' if role is made inactive, make sure that
        ' there are no active users in that role
        ' ----------------------------------------
        oldIsActive = CBool(e.OldValues(2))
        isActiveCheckBox = RolesScrollingGridView.Rows(e.RowIndex).FindControl("EditActiveCheckbox")
        newIsActive = CBool(isActiveCheckBox.Checked)
        If oldIsActive = True And newIsActive = False Then
            If CheckForActiveUsers(Convert.ToInt32(e.Keys.Item(0).ToString())) Then
                ShowStatus("Can not make this role inactive.  There are active users in this role.")
                e.Cancel = True
                Exit Sub
            End If
        End If

        ' Determine if there is a new value entered.
        If e.NewValues.Item(itemIndex) IsNot Nothing Then

            newValue = e.NewValues.Item(itemIndex).ToString.ToUpper
            ' Determine if the old value matches the new value.
            If oldValue = newValue Then

                If Me.ErrorSummary.Visible = True Then
                    Me.ErrorSummary.Visible = False
                End If

            Else

                For i As Integer = 0 To RolesScrollingGridView.Rows.Count - 1

                    If newValue = RolesScrollingGridView.Rows(i).Cells(1).Text.ToUpper Then
                        errorMessage = "Value already exists in the database. Please enter a different value."
                        ShowStatus(errorMessage)
                        e.Cancel = True
                        Me.ErrorSummary.Visible = True
                        Exit Sub
                    End If

                Next

                Me.ErrorSummary.Visible = False
                e.NewValues.Item(itemIndex) = Server.HtmlEncode(e.NewValues.Item(itemIndex).ToString())
                'Reset the application displaynames.
                System.Web.HttpContext.Current.Application("displayNames") = Nothing
            End If

        Else

            errorMessage = "You must enter a value in the field before updating."
            ShowStatus(errorMessage)
            'Me.ErrorSummary.Visible = True
            e.Cancel = True

        End If

    End Sub
End Class
